package com.itheima.controller;

import com.itheima.Service.DeptService;
import com.itheima.entity.Dept;
import com.itheima.entity.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 获取部门信息接口
 * @ResController：内含@Component
 */
//@Slf4j
@RestController
public class DeptController {
    private static final org.slf4j.Logger log = LoggerFactory.getLogger(DeptController.class);

    @Autowired
    private DeptService deptService;

    @GetMapping("/depts")
    public Result getAll() {
        //1.调用service，获取数据
        List<Dept> depts = deptService.list();

        //3.响应数据（json格式）
        return Result.success(depts);
    }

     // 方式三：当请求参数名和接收参数名称一致时
    @DeleteMapping("/depts")
    public Result delete(Integer id) {
//        System.out.println("id = " + id);
        log.info("id = {}", id); // 日志输出

        // Alt + Enter生成delete方法
        deptService.delete(id);

        return Result.success();
    }

    // 添加部门
    @PostMapping("/depts")
    public Result add(@RequestBody Dept dept) {   // 获取JSON对象
//        System.out.println("dept =" + dept);
        log.info("dept = {}", dept);
        deptService.add(dept);
        return Result.success();
    }

    // 根据id获取部门信息
    @GetMapping("/depts/{id}")
    public Result getById(@PathVariable Integer id) {
//        System.out.println("id = " + id);
        log.info("id = {}", id);
        Dept dept = deptService.getById(id);
        return dept == null ? Result.error("部门不存在") : Result.success(dept);
    }

    // 修改部门信息
    @PutMapping("/depts")
    public Result update(@RequestBody Dept dept) {
//        System.out.println("dept = " + dept);
        log.info("dept ={}", dept);

        deptService.update(dept);
        return Result.success();
    }
}
